/*
 * @lc app=leetcode.cn id=138 lang=javascript
 *
 * [138] 复制带随机指针的链表
 */

// @lc code=start
/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

/**
 * @param {Node} head
 * @return {Node}
 */
var copyRandomList = function(head) {
  if (!head) return head;
  for(let node = head; node; node = node.next) {
      const copyNode = new Node(node.val, node.next, null);
      node.next = copyNode;
      node = node.next;
  }
  for (let node = head; node; node = node.next) {
      const copyNode = node.next;
      copyNode.random = node.random !== null ? node.random.next : null;
      node = node.next;
  }
  const res = head.next;
  for (let node = head; node; node = node.next) {
      const copyNode = node.next;
      node.next = node.next.next;
      copyNode.next = copyNode.next !== null ? copyNode.next.next : null;
  }
  return res
};
// @lc code=end

